/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jserver.gameserver.custom;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.l2jserver.L2DatabaseFactory;
import com.l2jserver.gameserver.ThreadPoolManager;
import com.l2jserver.gameserver.faction.Faction;
import com.l2jserver.gameserver.faction.FactionManager;

/**
 * @author Sotrom
 *
 */
public class CrystalRank
{
	private final static HashMap<Integer, Integer> _factionsPoints = new HashMap<Integer, Integer>();
	private static Logger _log = Logger.getLogger(CrystalRank.class.getName());
	
	private CrystalRank()
	{
		
	}
	
	public static boolean isEmpty()
	{
		return _factionsPoints.isEmpty();
	}
	
	public static String getAnnounceText()
	{
		StringBuffer buffer = new StringBuffer();
		for (Integer id : _factionsPoints.keySet())
		{
			buffer.append(FactionManager.getFactionById(id).getName() + ": " + _factionsPoints.get(id) + ", ");
		}
		int end = buffer.length() - 2;
		return buffer.toString().substring(0, end);
	}
	
	@Deprecated
	public static void init()
	{
		/*Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("SELECT * FROM crystal_rank");
			ResultSet result = statement.executeQuery();
			
			while (result.next())
			{
				int factionId = result.getInt("faction_id");
				int points = result.getInt("points");
				_factionsPoints.put(factionId, points);
			}
			_log.info("CrystalRank loaded succesfully");
			
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, null, e);
		}
		finally
		{
			try
			{
				con.close();
			}
			catch (Exception e)
			{
			}
		}*/
	}
	
	public static void cleanTable()
	{
		Connection con = null;
		try
		{
			con = L2DatabaseFactory.getInstance().getConnection();
			PreparedStatement statement = con.prepareStatement("DELETE FROM crystal_rank");
			statement.executeUpdate();
			_log.info("CrystalRank cleaned succesfully");
			_factionsPoints.clear();
		}
		catch (Exception e)
		{
			_log.log(Level.SEVERE, null, e);
		}
		finally
		{
			try
			{
				con.close();
			}
			catch (Exception e)
			{
			}
		}
	}
	
	public static synchronized void increaseFactionPoint(Faction faction, int amount)
	{
		if (_factionsPoints.containsKey(faction.getFactionId()))
		{
			int oldVl = _factionsPoints.get(faction.getFactionId());
			oldVl += amount;
			_factionsPoints.put(faction.getFactionId(), oldVl);
			scheduleSave(faction.getFactionId(), oldVl);
		}
		else
		{
			_factionsPoints.put(faction.getFactionId(), amount);
			scheduleInsert(faction.getFactionId(), amount);
		}
	}
	
	/**
	 * @param factionId
	 * @param amount
	 */
	private static void scheduleInsert(int factionId, int amount)
	{
		ThreadPoolManager.getInstance().scheduleGeneral(new InsertPointTask(factionId, amount), (long) 500);
	}
	
	private static void scheduleSave(int factionId, int value)
	{
		ThreadPoolManager.getInstance().scheduleGeneral(new SavePointTask(factionId, value), (long) 500);
	}
	
	private static class InsertPointTask implements Runnable
	{
		private final int _id;
		private final int _vl;
		
		protected InsertPointTask(int id, int value)
		{
			_id = id;
			_vl = value;
		}
		
		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			Connection con = null;
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("INSERT INTO crystal_rank(faction_id,points) VALUES (?,?)");
				statement.setInt(1, _id);
				statement.setInt(2, _vl);
				statement.executeUpdate();
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, null, e);
			}
			finally
			{
				try
				{
					con.close();
				}
				catch (Exception e)
				{
				}
			}
		}
		
	}
	
	private static class SavePointTask implements Runnable
	{
		private final int _id;
		private final int _vl;
		
		protected SavePointTask(int id, int value)
		{
			_id = id;
			_vl = value;
		}
		
		/* (non-Javadoc)
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run()
		{
			Connection con = null;
			try
			{
				con = L2DatabaseFactory.getInstance().getConnection();
				PreparedStatement statement = con.prepareStatement("UPDATE crystal_rank SET points = ? WHERE faction_id = ?");
				statement.setInt(1, _vl);
				statement.setInt(2, _id);
				statement.executeUpdate();
				
			}
			catch (Exception e)
			{
				_log.log(Level.SEVERE, null, e);
			}
			finally
			{
				try
				{
					con.close();
				}
				catch (Exception e)
				{
				}
			}
		}
		
	}
	
}
